package com.dianrui.fmi.activity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dianrui.fmi.R;
import com.dianrui.fmi.util.CountDownTimerUtils;
import com.dianrui.fmi.util.MyUtil;
import com.dianrui.fmi.util.OkHttpUtils;
import com.dianrui.fmi.util.StringUtils;
import com.dianrui.fmi.util.ToastUtil;
import com.dianrui.fmi.util.Url;
import com.google.gson.JsonObject;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Buy or Sell
 */

public class OrderActivity extends BaseActivity {

    private String symbold, price, highs, lows, fullsymbol,type;
    private ProgressDialog mProgressDialog;
    private String direction;
    private String buy1s, buy2s, positions, servicechagres, deposit;
    private long ticks;

    @BindView(R.id.fullsymobel)
    TextView fullsymobel;
    @BindView(R.id.show_date)
    TextView showDate;
    @BindView(R.id.current_price)
    TextView currentPriceTxt;
    @BindView(R.id.high_price)
    TextView highPriceTxt;
    @BindView(R.id.low_price)
    TextView lowPriceTxt;
    @BindView(R.id.bid_price)
    EditText bidPrice;
    @BindView(R.id.stock_contract)
    TextView stockContract;
    @BindView(R.id.tips)
    TextView tips;

    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.account_balance)
    TextView accountBalance;

    @BindView(R.id.temp_lines)
    View tempLines;


    @BindView(R.id.order_price_number)
    EditText orderPriceNumber;

    @BindView(R.id.pl_cb)
    CheckBox plCb;
    @BindView(R.id.stop_price_number)
    EditText stopPriceNumber;

    @BindView(R.id.stop_layout_line)
    View stopLayoutLine;
    @BindView(R.id.stopl_price_number)
    EditText stoplPriceNumber;
    @BindView(R.id.stopl_layout_line)
    View stoplLayoutLine;
    @BindView(R.id.total)
    TextView total;

    @BindView(R.id.stop_layout)
    LinearLayout stopLayout;
    @BindView(R.id.stopl_layout)
    LinearLayout stoplLayout;
    @BindView(R.id.confirm_btn)
    Button confirmBtn;
    @BindView(R.id.tips_layout)
    LinearLayout tipsLayout;
    @BindView(R.id.tips_layout_line_layout)
    View tipsLayoutLineLayout;



    @BindView(R.id.inventory_charges)
    TextView inventoryCharges;
    @BindView(R.id.service_charges)
    TextView serviceCharges;
    @BindView(R.id.guarantee_money)
    TextView guaranteeMoney;


    @BindView(R.id.setting_p_l_layout)
    RelativeLayout settingPLLayout;
    @BindView(R.id.setting_p_l_line)
    View settingPLLine;


    @Override
    public int getContentViewId() {
        return R.layout.activity_stock_order;
    }

    @Override
    public void initView() {
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            ticks = bundle.getLong("tick");
            direction = bundle.getString("direction");
            fullsymbol = bundle.getString("fullsymbol");
            symbold = bundle.getString("symbold");
            price = bundle.getString("price");
            highs = bundle.getString("high");
            lows = bundle.getString("low");
            buy1s = bundle.getString("buy1");
            buy2s = bundle.getString("buy2");
            type=bundle.getString("type");


        }
        bidPrice.setSelection(bidPrice.length());
        orderPriceNumber.setSelection(orderPriceNumber.length());
        stopPriceNumber.setSelection(stopPriceNumber.length());
        stoplPriceNumber.setSelection(stoplPriceNumber.length());
        mProgressDialog = new ProgressDialog(OrderActivity.this);
        getDetails();
        getBalanaceInfo();
        title.setText(getString(R.string.transaction));
        highPriceTxt.setText(" " + highs);
        lowPriceTxt.setText(" " + lows);
        total.setText("$" + price);

        fullsymobel.setText(fullsymbol);

        if (direction.equals("1")) {
            confirmBtn.setBackgroundResource(R.drawable.green_shape);
        } else {
            confirmBtn.setBackgroundResource(R.drawable.orange_shape1);

        }

        detailsTimer.start();

        plCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    stopLayout.setVisibility(View.VISIBLE);
                    stopLayoutLine.setVisibility(View.VISIBLE);
                    stoplLayout.setVisibility(View.VISIBLE);
                    stoplLayoutLine.setVisibility(View.VISIBLE);
                    tempLines.setVisibility(View.GONE);
                } else {
                    stopLayout.setVisibility(View.GONE);
                    stopLayoutLine.setVisibility(View.GONE);
                    stoplLayout.setVisibility(View.GONE);
                    stoplLayoutLine.setVisibility(View.GONE);
                    tempLines.setVisibility(View.VISIBLE);
                }
            }
        });
        orderPriceNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() <= 0) {
                    ToastUtil.showToast("The Number is at least One!");
                    orderPriceNumber.setText("1");
                }
                orderPriceNumber.setSelection(orderPriceNumber.length());
            }
        });
        stopPriceNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() <= 0) {
                    ToastUtil.showToast("The Number is at least One!");
                    getDetails();
                }
                stopPriceNumber.setSelection(stopPriceNumber.length());
            }
        });
        stoplPriceNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() <= 0) {
                    ToastUtil.showToast("The Number is at least One!");
                    getDetails();
                }
                stoplPriceNumber.setSelection(stoplPriceNumber.length());
            }
        });
    }


    @SuppressLint("SetTextI18n")
    private void getDetails() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("symbol", fullsymbol);
        OkHttpUtils.getInstance().postWithMemberToken(Url.MARKERDETAILS, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                if (!StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("tips"))) {
                                    tips.setText(jsonObject.optJSONObject("data").optString("tips"));
                                    tipsLayout.setVisibility(View.VISIBLE);
                                    tipsLayoutLineLayout.setVisibility(View.VISIBLE);
                                }else {
                                    tipsLayout.setVisibility(View.GONE);
                                    tipsLayoutLineLayout.setVisibility(View.GONE);
                                }
                                currentPriceTxt.setText(jsonObject.optJSONObject("data").optString("price"));
                                bidPrice.setText(jsonObject.optJSONObject("data").optString("price"));
                                bidPrice.setSelection(bidPrice.length());
                                if (!StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("tick"))) {
                                    long l = jsonObject.optJSONObject("data").optLong("tick");
                                    String dates = new java.text.SimpleDateFormat("HH:mm:ss").format(new java.util.Date(l * 1000));
                                    showDate.setText(dates);
                                }
                                positions = jsonObject.optJSONObject("data").optString("position");
                                servicechagres = jsonObject.optJSONObject("data").optString("service_charge");
                                deposit = jsonObject.optJSONObject("data").optString("deposit");
                                if (jsonObject.optJSONObject("data").optString("zf").contains("-")) {
                                    currentPriceTxt.setTextColor(getResources().getColor(R.color.green_2ab23c));
                                } else {
                                    currentPriceTxt.setTextColor(getResources().getColor(R.color.red_deep));
                                }

                                //Show inventoryCharges
                                float receviedinventoryCharges = StringUtils.toFloat(jsonObject.optJSONObject("data").optString("position"));//position
                                float currentPriceNumber = StringUtils.toFloat(orderPriceNumber.getText().toString());//手数
                                float currentDeposit = StringUtils.toFloat(jsonObject.optJSONObject("data").optString("deposit"));//deposit
                                float InventoryChargesResult = currentDeposit * currentPriceNumber * receviedinventoryCharges;
                                inventoryCharges.setText(MyUtil.formatBy2Float(InventoryChargesResult, 2));//Swaps = deposit * number * position

                                //Show serviceCharges
                                float currentServiceCharge = StringUtils.toFloat(jsonObject.optJSONObject("data").optString("service_charge"));//手续费率
                                float currentServiceChargePrice = StringUtils.toFloat(orderPriceNumber.getText().toString());//手数
                                float ServiceChargeResult = currentServiceChargePrice * currentServiceCharge;//服务费=手续费率*number
                                serviceCharges.setText(MyUtil.formatBy2Float(ServiceChargeResult, 2));

                                //Show guaranteeMoney
                                float currentPrices = StringUtils.toFloat(jsonObject.optJSONObject("data").optString("deposit"));//deposit是保证金是意思
                                int num3 = StringUtils.toInt(orderPriceNumber.getText().toString());
                                float resultGuarantee = currentPrices * num3;//margin =  deposit * number
                                guaranteeMoney.setText(MyUtil.formatBy2Float(resultGuarantee, 2));

                                //show Total
                                float deposits = StringUtils.toFloat(jsonObject.optJSONObject("data").optString("deposit"));
                                float ordernumbers = StringUtils.toFloat(orderPriceNumber.getText().toString());
                                float servicechagre = StringUtils.toFloat(servicechagres);
                                float totalResult = deposits * ordernumbers + servicechagre * ordernumbers;
                                total.setText(MyUtil.formatBy2Float(totalResult, 2));//total = deposit * number + service_charge * number


                                float shop = StringUtils.toFloat(currentPriceTxt.getText().toString().trim());
                                float result2 = shop;
                                stopPriceNumber.setText(MyUtil.formatBy2Float(result2, 4));


                                float shopl = StringUtils.toFloat(currentPriceTxt.getText().toString().trim());
                                float result3 = shopl;
                                stoplPriceNumber.setText(MyUtil.formatBy2Float(result3, 4));
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void getBalanaceInfo() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("is_real", "1");
        OkHttpUtils.getInstance().postWithMemberToken(Url.GETBALACE, jsonObject.toString(),  new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                accountBalance.setText(jsonObject.optJSONObject("data").optString("balance"));
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {

                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });


    }

    CountDownTimerUtils detailsTimer = new CountDownTimerUtils(Long.MAX_VALUE, 5000) {
        @Override
        public void onTick(long millisUntilFinished) {
            getDetailsOne();
        }

        @Override
        public void onFinish() {

        }
    };


    @SuppressLint("SetTextI18n")
    private void getDetailsOne() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("symbol", fullsymbol);
        OkHttpUtils.getInstance().postWithMemberToken(Url.MARKERDETAILS, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                if (direction.equals("1")) {
                                    currentPriceTxt.setText(jsonObject.optJSONObject("data").optString("price"));
                                    bidPrice.setText(jsonObject.optJSONObject("data").optString("price"));
                                    bidPrice.setSelection(bidPrice.length());
                                } else {
                                    currentPriceTxt.setText(jsonObject.optJSONObject("data").optString("price"));
                                    bidPrice.setText(jsonObject.optJSONObject("data").optString("price"));
                                    bidPrice.setSelection(bidPrice.length());
                                }
                                if (!StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("tick"))) {
                                    long l = jsonObject.optJSONObject("data").optLong("tick");
                                    String dates = new java.text.SimpleDateFormat("HH:mm:ss").format(new java.util.Date(l * 1000));
                                    showDate.setText(dates);
                                }
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }


    @OnClick({R.id.back, R.id.order_minus_sel, R.id.order_minus_add, R.id.stop_minus_sel, R.id.stop_minus_add, R.id.stopl_minus_sel, R.id.stopl_minus_add, R.id.confirm_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                if (detailsTimer != null) {
                    detailsTimer.cancel();
                }
                finish();
                break;

            case R.id.order_minus_sel:
                float currentPrice = StringUtils.toFloat(deposit);
                int num2 = StringUtils.toInt(orderPriceNumber.getText().toString());
                if (num2 > 1) {
                    num2 -= 1;
                }
                orderPriceNumber.setText(num2 + "");
                orderPriceNumber.setSelection(orderPriceNumber.length());
                float result = currentPrice * num2;
                guaranteeMoney.setText(MyUtil.formatBy2Float(result, 2));//margin =  deposit * 手数

                float currentdeposit = StringUtils.toFloat(deposit);
                float currentinventoryPriceAdd1 = StringUtils.toFloat(positions);
                float currentinventoryadd1 = StringUtils.toFloat(orderPriceNumber.getText().toString());
                float inventoryResultAdd1 =currentdeposit* num2 * currentinventoryPriceAdd1;
                inventoryCharges.setText(MyUtil.formatBy2Float(inventoryResultAdd1, 2));//Swaps = deposit * 手数 * position

                float currentSeviceadd1 = StringUtils.toFloat(servicechagres);
                float currentserviceadd1 = StringUtils.toFloat(orderPriceNumber.getText().toString());
                double serviceResultAdd1 = num2 * currentSeviceadd1;
                serviceCharges.setText(MyUtil.formatBy2double(serviceResultAdd1, 2));//服务费=手续费率*手数


                float currentinventoryCharges = StringUtils.toFloat(deposit);
                float currentserviceCharges = StringUtils.toFloat(servicechagres);
                float currentguaranteeCharges = StringUtils.toFloat(num2);
                float totalResult = currentinventoryCharges * num2 + currentserviceCharges*num2;
                total.setText(MyUtil.formatBy2Float(totalResult, 2));//total = deposit * 手数 + service_charge * 手数

                break;

            case R.id.order_minus_add:
                orderPriceNumber.setSelection(orderPriceNumber.length());
                float currentPrice1 = StringUtils.toFloat(deposit);
                int num31 = StringUtils.toInt(orderPriceNumber.getText().toString());
                num31 += 1;
                orderPriceNumber.setText(num31 + "");
                float result1 = currentPrice1 * num31;
                guaranteeMoney.setText(MyUtil.formatBy2Float(result1, 2));


                float currentinventoryPriceAdd = StringUtils.toFloat(deposit);
                float currentinventoryadd = StringUtils.toFloat(orderPriceNumber.getText().toString());
                float currentdepositAdd = StringUtils.toFloat(positions);
                float inventoryResultAdd = currentinventoryadd * currentinventoryPriceAdd*currentdepositAdd;
                inventoryCharges.setText(MyUtil.formatBy2Float(inventoryResultAdd, 2));//Swaps = deposit * 手数 * position

                float currentSeviceadds = StringUtils.toFloat(servicechagres);
                float currentserviceadd = StringUtils.toFloat(orderPriceNumber.getText().toString());
                double serviceResultAdd = currentserviceadd * currentSeviceadds;
                serviceCharges.setText(MyUtil.formatBy2double(serviceResultAdd, 2));


                float currentinventoryCharges1 = StringUtils.toFloat(deposit);
                float currentserviceCharges2 = StringUtils.toFloat(servicechagres);
                float currentguaranteeCharges3 = StringUtils.toFloat(num31);
                float totalResult1 = currentinventoryCharges1 * currentguaranteeCharges3+currentserviceCharges2*currentguaranteeCharges3;
                total.setText(MyUtil.formatBy2Float(totalResult1, 2));//total = deposit * 手数 + service_charge * 手数
                break;


            case R.id.stop_minus_sel:
                BigDecimal num = new BigDecimal(stopPriceNumber.getText().toString());
                double f = num.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                if (f > 0.0001) {
                    f -= 0.0001;
                }
                stopPriceNumber.setText(MyUtil.formatBy2double(f, 4) + "");
                stopPriceNumber.setSelection(stopPriceNumber.length());
                break;
            case R.id.stop_minus_add:
                BigDecimal num1 = new BigDecimal(stopPriceNumber.getText().toString());
                double f1 = num1.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                f1 += 0.0001;
                stopPriceNumber.setText(MyUtil.formatBy2double(f1, 4) + "");
                stoplPriceNumber.setSelection(stoplPriceNumber.length());
                break;

            case R.id.stopl_minus_sel:
                BigDecimal num3 = new BigDecimal(stoplPriceNumber.getText().toString());
                double f2 = num3.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                if (f2 > 0.0001) {
                    f2 -= 0.0001;
                    stoplPriceNumber.setText(MyUtil.formatBy2double(f2, 4) + "");
                }
                break;

            case R.id.stopl_minus_add:
                BigDecimal num4 = new BigDecimal(stoplPriceNumber.getText().toString());
                double f3 = num4.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                f3 += 0.0001;
                stoplPriceNumber.setText(MyUtil.formatBy2double(f3, 4) + "");
                break;

            case R.id.confirm_btn:
                if (detailsTimer != null) {
                    detailsTimer.cancel();
                }
                SubmitOrder();
                break;

            default:
                break;
        }
    }

    private void SubmitOrder() {
        mProgressDialog.setMessage(getString(R.string.submiting));
        mProgressDialog.show();
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setCancelable(false);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("symbols_id", symbold);
        jsonObject.addProperty("number", orderPriceNumber.getText().toString().trim());
        jsonObject.addProperty("type", type);
        jsonObject.addProperty("direction", direction);
        if (plCb.isChecked()) {
            jsonObject.addProperty("max_price", stopPriceNumber.getText().toString().trim());
            jsonObject.addProperty("min_price", stoplPriceNumber.getText().toString().trim());
        }
        OkHttpUtils.getInstance().postWithMemberToken(Url.SUBMITORDER, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                mProgressDialog.dismiss();
                                Intent intent = new Intent(OrderActivity.this, SimulatedTransactionNewActivity.class);
                                intent.putExtra("pageType", "2");
                                intent.putExtra("pageback", "2");
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                                ToastUtil.showToast(jsonObject.optString("message"));
                                finish();

                            } else {
                                mProgressDialog.dismiss();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    mProgressDialog.dismiss();
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        if (detailsTimer != null) {
            detailsTimer.cancel();
        }
    }
}
